<template>
  <view
    class="page_root"
    data-page-name="新建其他日报（定制）"
    data-page-identification="a_rguwr23liw"
  >
    <!-- UNI_APP_EXEGESIS_START NAVIGATION_TEMPLATE UNI_APP_EXEGESIS_END -->
    <!-- begin vid_ivbdkd2yl0 自定义模板_shihqlccwh -->
    <u-mask :show="maskShow" @click="show = false">
      <view class="warp">
        <view class="rect">{{ maskTip }} </view>
      </view>
    </u-mask>
    <u-navbar
      back-icon-color="#fff"
      title="新建其他日报"
      title-color="#fff"
      :border-bottom="false"
      title-width="350"
    >
    </u-navbar>
    <view class="body">
      <view class="bot-bgc"></view>
      <view class="top-title">
        <view class="positioning"></view>
        <u-notice-bar
          mode="horizontal"
          bg-color="rgba(51,102,255,0.10)"
          :list="recordState.topList"
          color="#3366FF"
          :volume-icon="false"
          border-radius="8"
        ></u-notice-bar>
      </view>
      <u-form :model="recordState" ref="recordForm" :rules="rules">
        <u-picker
          v-model="recordState.dateShow"
          mode="time"
          title="请选择工时提交日期"
          @cancel="onCancel"
          @confirm="dailyDateConfirm"
        ></u-picker>
        <u-form-item
          required="true"
          label-position="top"
          label="请选择工时提交日期"
          prop="dailyDate"
        >
          <u-input
            border="true"
            placeholder="请选择工时提交日期"
            type="select"
            v-model:modelValue="recordState.dailyDate"
            @click="recordState.dateShow = true"
          ></u-input>
        </u-form-item>
        <u-select
          v-model="recordState.projectCodeShow"
          mode="single-column"
          title="请选择工作类型"
          :list="recordState.projectCodeList"
          @confirm="onProjectConfirm"
        ></u-select>
        <u-form-item required="true" label-position="top" label="工作类型" prop="projectCode">
          <u-input
            border="true"
            placeholder="请选择工作类型"
            type="select"
            v-model:modelValue="recordState.projectCode"
            @click="getProjectList"
          ></u-input>
        </u-form-item>
        <u-form-item required="true" label-position="top" label="工时" prop="workingHours">
          <u-input
            type="digit"
            border="true"
            placeholder="请输入工时(支持0.5的数字)"
            v-model:modelValue="recordState.workingHours"
          ></u-input>
        </u-form-item>
        <!-- <u-form-item required="true" label-position="top" label="工作内容" prop="dailyContent">
          <u-input clearable="true" border="true" placeholder="请输入事项描述" v-model:modelValue="recordState.dailyContent"></u-input>
        </u-form-item> -->
      </u-form>
    </view>
    <u-row justify="space-around" style="margin-top: 24px">
      <u-col span="4">
        <u-button :custom-style="customStyle" @click="handlerCancel">取消</u-button>
      </u-col>
      <u-col span="4">
        <u-button :custom-style="customStyle" @click="handlerSubmit(false)">保存</u-button>
      </u-col>
      <u-col span="4">
        <u-button :custom-style="customStyleSubmit" @click="handlerSubmit(true)"
          >保存并提交</u-button
        >
      </u-col>
      <!-- <u-col span="4">
        <u-button :custom-style="customStyle" @click="handlerSubmitAndAdd">保存并新增</u-button>
      </u-col> -->
    </u-row>
    <u-modal
      v-model="recordState.show"
      show-cancel-button
      @confirm="handleConfirmSubmit"
      title="请确认"
      :title-style="{ padding: 0, marginTop: '10px', marginBottom: '10px' }"
    >
      <view class="sub-tip">
        正在提交工时：{{ recordState.editHour }}工时 <br />
        今日已提交总工时(不含本次提交)：{{ Number(recordState.allHour )+parseFloat(recordState.editHour) }}工时
      </view>
    </u-modal>
    <!-- end vid_ivbdkd2yl0 自定义模板_shihqlccwh -->
  </view>
</template>
<script setup>
  import {
    ref,
    reactive,
    toRaw,
    markRaw,
    watch,
    computed,
    onBeforeMount,
    onMounted,
    onBeforeUnmount,
    onUnmounted,
    onActivated,
    onDeactivated,
    getCurrentInstance,
  } from 'vue';
  import { useRoute } from 'vue-router';
  const route = useRoute();
  import { get, post, put, del, request, requestWithHeaders } from '@/utils/http/Axios';
  import {
    cloneDeep,
    localGet,
    traversalTreeStructure,
    set,
    checkCaseCondition,
    throttle,
    merge,
    debounce,
    getGridStyle,
    getCellRenderAble,
  } from '@/utils/index';
  import {
    isEqual,
    isNullOrEmpty,
    isEmptyArr,
    isArray,
    isEmpty,
    isNullOrUnDef,
    isContained,
  } from '@/utils/is';
  import { CovertOptions, getChartsDataSourceConvert } from '@/utils/chart';
  import {
    propertyFormatByNumber,
    propertyFormatByPercentage,
    propertyFormatByDate,
  } from '@/utils/format';
  import { FormFormat } from '@/utils/formFormat';
  import { customAddWaterMarkFunc, generateWaterMarkText } from '@/utils/addWaterMark';
  import dayjs from 'dayjs';
  import hashSum from 'hash-sum';
  import { handleRedirect } from '@/utils/common';
  import {
    onPullDownRefresh,
    onLoad,
    onReady,
    onShow,
    onHide,
    onPageScroll,
    onUnload,
  } from '@dcloudio/uni-app';
  /*** UNI_APP_EXEGESIS ***
  import { handleRedirect, permission, parseJson } from '@/utils/common';
  import { onPullDownRefresh, onLoad, onReady, onShow, onHide, onPageScroll, onUnload } from '@dcloudio/uni-app';
  import { BroadcastMessage } from '@/utils/BroadcastMessage';
  import { sendToken } from "@/hooks/useIframeToken";
  *** UNI_APP_EXEGESIS ***/

  // ---------------------------- 属性定义 ----------------------------
  const sourceId = 'page50001907';

  // 是否显示菜单按钮
  const isMenuIconShow = false;
  // NAVIGATION_MENU
  const handleShowNavigation = () => {};

  let isProcessState = ref(false);

  const setTimeOutList = [];

  const vid_ivbdkd2yl0_props = reactive({
    code: '    <u-mask :show="maskShow" @click="show = false">  \n    <view class="warp">\n\n      <view class="rect" >{{ maskTip }} </view>\n    </view>\n    </u-mask>\n    <view class="bgc-img"></view>\n    <view class="body">\n      <u-notice-bar mode="horizontal" :list="recordState.topList"></u-notice-bar>\n      <u-form :model="recordState" ref="recordForm" :rules="rules">\n        <u-picker v-model="recordState.dateShow" mode="time" title="请选择工时提交日期" @cancel="onCancel" @confirm="dailyDateConfirm"></u-picker>\n        <u-form-item required="true" label-position="top" label="请选择工时提交日期" prop="dailyDate">\n          <u-input border="true" placeholder="请选择工时提交日期" type="select" v-model:modelValue="recordState.dailyDate" @click="recordState.dateShow = true"></u-input>\n        </u-form-item>\n        <u-select v-model="recordState.projectCodeShow" mode="single-column" title="请选择工作类型" :list="recordState.projectCodeList" @confirm="onProjectConfirm"></u-select>\n        <u-form-item required="true" label-position="top" label="工作类型" prop="projectCode">\n          <u-input border="true" placeholder="请选择工作类型" type="select" v-model:modelValue="recordState.projectCode" @click="getProjectList"></u-input>\n        </u-form-item>\n        <u-form-item required="true" label-position="top" label="工时" prop="workingHours">\n          <u-input type="number" border="true" placeholder="请输入工时(支持0.5的数字)" v-model:modelValue="recordState.workingHours"></u-input>\n        </u-form-item>\n        <!-- <u-form-item required="true" label-position="top" label="工作内容" prop="dailyContent">\n          <u-input clearable="true" border="true" placeholder="请输入事项描述" v-model:modelValue="recordState.dailyContent"></u-input>\n        </u-form-item> -->\n      </u-form>\n    </view>\n    <u-row justify="space-around" style="margin-top: 24px">\n      <u-col span="4">\n        <u-button :custom-style="customStyle" @click="handlerCancel">取消</u-button>\n      </u-col>\n      <u-col span="4">\n        <u-button :custom-style="customStyle" @click="handlerSubmit(false)">保存</u-button>\n      </u-col>\n      <u-col span="4">\n        <u-button :custom-style="customStyle" @click="handlerSubmit(true)">保存并提交</u-button>\n      </u-col>\n      <!-- <u-col span="4">\n        <u-button :custom-style="customStyle" @click="handlerSubmitAndAdd">保存并新增</u-button>\n      </u-col> -->\n    </u-row>\n    <u-modal v-model="recordState.show" show-cancel-button @confirm="handleConfirmSubmit" title="请确认" :title-style="{padding:0,marginTop:\'10px\',marginBottom:\'10px\'}" >\n      <view class="sub-tip">\n        <view class="sub-title">\n          正在提交工时：{{recordState.editHour}}工时 <br />\n          今日已提交总工时(不含本次提交)：{{Number(recordState.allHour+recordState.editHour)}}工时</view\n        >\n      </view>\n    </u-modal>',
  });

  // ============================ 属性定义 ============================

  // ---------------------------- 元素数据引用 ----------------------------
  // 组件 自定义模板_shihqlccwh ref 的引用
  const vid_ivbdkd2yl0_ref = ref(null);
  // 动态key的map
  const fieldTypeMap = {};
  // 动态key的map
  const refMap = { vid_ivbdkd2yl0_ref };

  const showState = reactive({
    vid_ivbdkd2yl0_visible: true,
  });
  // ============================ 元素数据引用 ============================

  // ---------------------------- 数据 ----------------------------

  // ============================ 数据 ============================

  // ---------------------------- 方法 ----------------------------
  // ---------------------------- 页面数据 ----------------------------

  // ============================ 页面数据 ============================

  // ---------------------------- 响应 ----------------------------

  // ============================ 响应 ============================

  // ---------------------------- 函数 ----------------------------

  // 自定义函数 返回上一页
  const customFunction_goBack_iw7h9p8j0q = (...params) => {
    uni.navigateBack();
  };

  // ============================ 函数 ============================

  // ---------------------------- 页面参数 ----------------------------

  const pageParameter_state = reactive({
    processInstanceId: undefined,
  });

  // ============================ 页面参数 ============================

  // ---------------------------- 组件事件处理方法 ----------------------------

  // ============================ 组件事件处理方法 ============================

  // ============================ 方法 ============================

  // ---------------------------- 生命周期 ----------------------------
  /*** UNI_APP_EXEGESIS ***
      // 获取上一层传递的数据
      const workflowChannel = new BroadcastMessage('WORKFLOW');
      workflowChannel.publish({ status: 'Ready' });
      workflowChannel.subscribe((data) => {
        if (data) {
          isProcessState.value = (window.self !== window.parent && data.type === 'hideHeader');
        }
      });
      *** UNI_APP_EXEGESIS ***/

  const pageScrollTop = ref(0);

  // *** PREVIEW_EXEGESIS ***
  onMounted(() => {
    setPageParams(route.query);
    // 设置表单的rule
    try {
    } catch {
      // do nothing
    }
  });
  // *** PREVIEW_EXEGESIS *** //

  /*** UNI_APP_EXEGESIS ***
  const routeOption = ref({})
  onLoad((option) => {
    routeOption.value = option;
  });
  onReady(() => {
    setPageParams(routeOption.value)
    // 设置表单的rule
    try{

    }catch{
        // do nothing
    }
  });
  // 图表刷新标记
  const uChartsReshowFlag = ref(false);
  onHide(() => { // 页面隐藏后标记置为false(如果不置为false无法触发图表更新)
      uChartsReshowFlag.value = false
  })
  onShow(() => {
      uChartsReshowFlag.value = true; // 页面激活后,标记置为true

      setPageParams(routeOption.value)
  })
  onPageScroll(e => {
      pageScrollTop.value = e.scrollTop
  });
  *** UNI_APP_EXEGESIS ***/

  const setPageParams = (routerParam) => {
    const pageParams = [{ dataType: 'STRING', dependencies: [], name: 'processInstanceId' }];
    const strategyMap = {
      STRING: (param, paramValue) => {
        pageParameter_state[param.name] = paramValue;
      },
      BOOLEAN: (param, paramValue) => {
        if ('true' === (paramValue || '').toLowerCase()) {
          pageParameter_state[param.name] = true;
        } else if ('false' === (paramValue || '').toLowerCase()) {
          pageParameter_state[param.name] = false;
        } else {
          // TODO: 是否要支持toast
          console.error('参数传入错误！类型不匹配！');
        }
      },
      NUMBER: (param, paramValue) => {
        if (!isNaN(paramValue)) {
          pageParameter_state[param.name] = Number(paramValue);
        } else {
          // TODO: 是否要支持toast
          console.error('参数传入错误！类型不匹配！');
        }
      },
      ARRAY: (param, paramValue) => {
        if (isNullOrUnDef(paramValue) || !paramValue || paramValue === 'undefined') {
          // default value
          pageParameter_state[param.name] = [];
        } else if (paramValue.trim().startsWith('[') && paramValue.trim().endsWith(']')) {
          try {
            pageParameter_state[param.name] = JSON.parse(decodeURI(paramValue));
          } catch (error) {
            console.error('参数解析失败 ', error);
          }
        } else {
          console.error('参数传入错误！类型不匹配！');
        }
      },
    };
    pageParams.forEach((param) => {
      strategyMap[param.dataType](param, routerParam[param.name]);
    });
  };

  onUnmounted(() => {
    // 销毁定时器
    setTimeOutList.forEach(({ repeat, timer }) => {
      repeat ? clearInterval(timer) : clearTimeout(timer);
    });
  });

  /*** UNI_APP_EXEGESIS ***
  onPullDownRefresh(() => {
    // 下拉刷新
    setTimeout(() => {
        uni.stopPullDownRefresh()
    }, 1000)
  })
  *** UNI_APP_EXEGESIS ***/

  // ============================ 生命周期 ============================

  // ---------------------------- 数据关联处理 ----------------------------
  // ---------------------------- 组件数据同步 ----------------------------

  // ============================ 组件数据同步 ============================
  //
  // ============================ 数据关联处理 ============================

  // ---------------------- 不同组件自定义的处理逻辑 ---------------------

  // ====================== 不同组件自定义的处理逻辑 ======================

  // ================================定制化逻辑========================================
  onMounted(() => {
    try {
      recordForm?.value?.setRules(rules);
      setPageStyle('qtrb-page');
      getNumber()
    } catch {
      // do nothing
    }
  });
  
  function setPageStyle(newClass) {
    // #ifdef H5
    // 仅在 H5 执行
    const appDiv = document.querySelector('#app');
    if (appDiv) {
      appDiv.className = '';

      // 再添加当前需要的类
      appDiv.className = '';
      if (newClass) {
        appDiv.classList.add(newClass);
      }
    }

    const topHeader = document.querySelector('.uni-page-head');
    if (topHeader) topHeader.remove();

    const wrapper = document.querySelector('uni-page-wrapper');
    if (wrapper) wrapper.style.height = '100%';
    // #endif

    // #ifdef MP
    // 小程序端执行（如果你要做兼容逻辑，可以写这里）
    console.log('当前是小程序环境，不需要处理头部或背景');
    // #endif
  }
  const recordForm = ref(null);
  const rules = {
    dailyDate: [
      {
        type: 'string',
        required: true,
        message: '请选择工时提交日期',
        trigger: ['blur', 'change'],
      },
    ],
    projectCode: [
      { type: 'string', required: true, message: '请选择工作类型', trigger: ['blur', 'change'] },
    ],
    workingHours: [
      {
        required: true,
        validator: validateWorkingHours,
        trigger: ['blur', 'change'],
      },
    ],
    dailyContent: [
      { type: 'string', required: true, message: '请输入事项描述', trigger: ['blur', 'change'] },
    ],
  };
  function validateWorkingHours(rule, value, callback) {
    if (!/^(0(\.5)?|[1-7](\.0|\.5)?|8(\.0)?)$/.test(value)) {
      callback(new Error('请输入有效的工时(支持0.5的数字)'));
    } else {
      callback();
    }
  }
  const customStyle = reactive({
    backgroundColor: '#fff',
    color: ' rgba(0,0,0,0.65)',
    borderRadius: '4px',
    fontWeight: '500',
    borderColor: '#fff',
  });
  const customStyleSubmit = reactive({
    borderRadius: '8rpx',
    backgroundImage: 'linear-gradient(-67deg, #82B0FF 0%, #3366FF 74%)',
    borderColor: '#fff',
    color: '#fff',
  });
  // 定制化逻辑
  const recordState = reactive({
    isStage: false,
    dateShow: false,
    dailyDate: '',
    projectCodeShow: false,
    // 项目选择列表
    projectCodeList: [],
    // 选中的项目id
    projectCode: undefined,
    workingHours: null,
    dailyContent: '',
    show: false,
    editHour: 0,
    allHour: 0,
    topList: [],
  });
  var currentURL = window.location.href;
  if (currentURL.includes('stage')) {
    recordState.isStage = true;
  } else {
    recordState.isStage = false;
  }
  const formattedDate = dayjs().format('YYYY-MM-DD');
  recordState.dailyDate = formattedDate;

  function dailyDateConfirm(params) {
    const formattedDate = dayjs.unix(params.timestamp).format('YYYY-MM-DD');
    recordState.dailyDate = formattedDate;
    getNumber()
  }
  // 获取工作类型
  function getProjectList() {
    post('/solution-ppm/api/v2/built-in-system-ppm/jobCategory/jobCategoryList').then((data) => {
      recordState.projectCodeList = data.data.map((item) => {
        return {
          value: item.jobCategoryId,
          label: item.jobCategory,
        };
      });
      recordState.projectCodeShow = true;
    });
  }
  // 取消按钮
  function handlerCancel() {
    backHomePage();
  }
  function getNumber(){
post('/solution-ppm/api/v2/built-in-system-ppm/daily_report/for_create', {
    dailyDate: recordState.dailyDate,
  }).then((data) => {
    recordState.allHour = data.data.workHours;
    recordState.topList = [
      `正在编辑工时：${
        recordState.workingHours ? recordState.workingHours : 0
      }工时,今日已提交总工时（不含本次提交）${recordState.allHour}工时`,
    ];
  });
  }
  

  const maskShow = ref(false);
  const maskTip = ref('正在保存请稍后...');
  // 保存日报
  function handlerSubmit(flag) {
    recordForm.value.validate().then(() => {
      recordState.isSaveAndSubmit = flag;
      if (flag === false) {
        handleConfirmSubmit();
      } else {
        recordState.show = true;
      }
    });
  }
  function handleConfirmSubmit() {
    maskShow.value = true;
    if (recordState.isSaveAndSubmit) {
      maskTip.value = '正在提交请稍后...';
    } else {
      maskTip.value = '正在保存请稍后...';
    }
    const params = {
      // dailyDate: recordState.dailyDate,
      // ppmDailyItem:[{code:recordState.projectCode}]
      // projectCode: recordState.projectCode,
      // workingHours: recordState.workingHours,
      // dailyContent: recordState.dailyContent,
      //      dailyType:
      ppmDailyItems: [
        {
          projectCode: recordState.projectCode,
          dailyType: '3',
          workingHours: recordState.workingHours,
        },
      ],
      dailyDate: recordState.dailyDate,
      dailyType: '3',

      isSubmit: recordState.isSaveAndSubmit === true ? true : false,
    };
    post('/solution-ppm/api/v2/built-in-system-ppm/daily/add/PpmDaily', params).then((data) => {
      if (data.code === 200) {
        if (recordState.isSaveAndSubmit) {
          uni.showToast({
            title: '提交成功',
            icon: 'success',
          });
          recordState.show = false;
          maskShow.value = false;
          backHomePage();
        } else {
          uni.showToast({
            title: '保存成功',
            icon: 'success',
          });
          recordState.show = false;
          maskShow.value = false;
          backHomePage();
        }
      } else {
        uni.showToast({
          title: `${data.message}`,
          icon: 'error',
        });
        maskShow.value = false;
      }
    });
  }

  const backHomePage = async () => {
    const isLocal = window.location.host.includes('localhost');
    const url = isLocal ? '/pages/home/home' : '/pages/Page3000001233/Page3000001233';
    handleRedirect(url);
  };
  // 工作类型确定
  function onProjectConfirm(params) {
    recordState.projectCode = params[0].label;
  }
  watch(
    () => recordState.workingHours,
    () => {
      recordState.editHour = recordState.workingHours;
      recordState.topList = [
        `正在编辑工时：${
          recordState.workingHours ? recordState.workingHours : 0
        }工时,今日已提交总工时（不含本次提交）${recordState.allHour}工时`,
      ];
    },
    { deep: true },
  );
</script>
<style lang="less" scoped>
  .page_root {
    box-sizing: border-box;
    background-image: url('http://10.40.0.33:9001/file-storage/540437262415247360-source.png');
    background-size: cover;
    padding: 40rpx;
  }

  .body {
    height: 100%;
    padding: 12px;
    border-radius: 10px;
    background-image: url('http://10.40.0.33:9001/file-storage/540452806172424192-source.png');
    background-size: cover;
    position: relative;
    top: 15px;
  }
  .top-title {
    display: flex;
  }
  .positioning {
    width: 220rpx;
  }
  .bot-bgc {
    width: 100rpx;
    height: 140rpx;
    position: absolute;
    background-image: url('http://10.40.0.33:9001/file-storage/540452924739106816-source.png');
    background-size: cover;
    z-index: 2;
    left: 36rpx;
    top: -36rpx;
  }

  .warp {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
  }

  .rect {
    width: 120px;
    height: 120px;
    color: #fff;
  }
  .sub-title {
    padding: 0 15px;
    font-size: 14px;
  }
  :deep(.u-navbar) {
    background-color: transparent !important;
    padding: 0 40rpx 0 0;
    border: none;
  }
  :deep(.u-input) {
    background-color: #fff;
  }
</style>
